package com.zhanlv.socketnet;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class RemoteActivity extends AppCompatActivity {

    Socket socket;
    InputStream inputStream;

    OutputStream outputStream;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remote);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(
                        Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 10000);
                //return;
            }
        }

        /*new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    socket = new Socket("139.196.17.31", 6667);
                    outputStream = socket.getOutputStream();
                    inputStream = socket.getInputStream();

                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();*/



        findViewById(R.id.btn_test).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            testMp3();
                        }catch (JSONException e){

                        } catch (IOException e) {

                        }
                    }
                }).start();

            }
        });

        /*new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try{
                        Thread.sleep(3000);
                        Log.e("wooran", "777777777777");
                        byte[] response = new byte[1024];

                        int readIndex = inputStream.read(response);
                        Log.e("wooran", "readIndex is " + readIndex + " inputstream eqal: " + inputStream);


                    }catch (Exception e){

                    }
                }
            }
        }).start();*/
    }

    void test() throws JSONException, IOException {
        /*JSONObject jsonObject = new JSONObject();
        jsonObject.put("text", "helloid 123456");
        jsonObject.put("language", "zh-cn");
        jsonObject.put("voiceName", "zh-cn-XiaoxiaoMultilingualNeural");
        jsonObject.put("speechRate", 1);
        jsonObject.put("voiceStyle", "Newscast");
        jsonObject.put("quality", 1);

        String jsonStr = jsonObject.toString();
        String payload = "${jsonStr.length}\n$jsonStr";*/

        socket = new Socket("127.0.0.1", 6667);
        outputStream = socket.getOutputStream();
        inputStream = socket.getInputStream();


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("androidId", "helloid 123456");

        String jsonStr = jsonObject.toString();
        String payload = jsonStr.length() + "\n" + jsonStr;

        Log.e("wooran", "111111111111111111");

        Log.e("wooran", "222222222222222222");
        Log.e("wooran", "status " + socket.isConnected());

        /*try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }*/

        Log.e("wooran", "33333333333333");
        Log.e("wooran", "status " + socket.isConnected());


        /*outputStream.write(payload.getBytes(StandardCharsets.UTF_8));
        byte[] response = new byte[30];
        inputStream.read(response, 0, 30);

        String[] lengths = (new String(response)).split("\n");

        Log.e("wooran", "lengths: ");
        for(int i=0; i<lengths.length; i++){
            Log.e("wooran", String.valueOf(Integer.parseInt(lengths[i])));
        }*/

        Log.e("wooran", "5555555555555");
        outputStream.write(payload.getBytes(StandardCharsets.UTF_8));
        Log.e("wooran", "66666666666666");

        /*try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }*/


        Log.e("wooran", "777777777777");
        byte[] response = new byte[20];

        int readIndex = inputStream.read(response, 0, 20);
        Log.e("wooran", "readIndex is " + readIndex + " inputstream eqal: " + inputStream);

        String resStr = new String(response);
        Log.e("wooran", "response is " + resStr);

        Double resDouble = Double.valueOf(Double.parseDouble(resStr));

        Log.e("wooran", "double is " + resDouble);

                        /*String resStr = new String(response, 0, readIndex, StandardCharsets.UTF_8);
                        Log.e("wooran", "response is " + resStr);*/


        /*while (inputStream.read(response) != -1){

        }
        inputStream.read(response);


        Log.e("wooran", "response is " + (new String(response, StandardCharsets.UTF_8)));*/

    }

    void testMp3() throws JSONException, IOException {
        //139.196.17.31
        socket = new Socket("127.0.0.1", 6667);
        outputStream = socket.getOutputStream();
        inputStream = socket.getInputStream();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("text", "今天多少号");
        jsonObject.put("language", "zh-cn");
        jsonObject.put("voiceName", "zh-cn-XiaoxiaoMultilingualNeural");
        jsonObject.put("speechRate", 1);
        jsonObject.put("voiceStyle", "Newscast");
        jsonObject.put("quality", 1);

        String jsonStr = jsonObject.toString();
        String payload = jsonStr.length() + "\n" + jsonStr;

        outputStream.write(payload.getBytes(StandardCharsets.UTF_8));

        byte[] lengthInfo = new byte[30];
        inputStream.read(lengthInfo, 0, 30);

        Log.i("wooran", "response is " + new String(lengthInfo));

        String[] split = new String(lengthInfo).split("\n");

        Log.i("wooran", "split is " + split[0] + "," + split[1] + "," + split[2]);

        int scoreLength = Integer.parseInt(split[0]);
        int labLength = Integer.parseInt(split[1]);
        int mp3Length = Integer.parseInt(split[2]);

        Log.i("wooran", "length: " + scoreLength + "," + labLength + "," + mp3Length);

        byte[] scoreByte = new byte[scoreLength];
        byte[] labByte = new byte[labLength];
        byte[] mp3Byte = new byte[mp3Length];

        int i=0;
        while (i<scoreLength){
            i += inputStream.read(scoreByte, 0, scoreLength - i);
        }
        Double score = Double.valueOf(Double.parseDouble(new String(scoreByte)));
        Log.i("wooran", "score " + score);

        int i1 = 0;
        while (i1 < labLength){
            i1 += inputStream.read(labByte, 0, labLength - i1);
        }

        int i2 = 0;
        while (i2 < mp3Length){
            i2 += inputStream.read(mp3Byte, i2, mp3Length - i2);
        }

        String mp3Path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();

        FileOutputStream mp3Stream = new FileOutputStream(mp3Path + "/wooranmp31312345.mp3");
        mp3Stream.write(mp3Byte);
        mp3Stream.flush();
        mp3Stream.close();

        FileOutputStream labStream = new FileOutputStream(mp3Path + "/wooranmp31312345.lab");
        /*for(int i3=0; i3<labLength; i3++){
            labByte[i3] = (byte) (labByte[i3] + i3);
        }*/
        labStream.write(labByte);
        labStream.flush();
        labStream.close();
    }
}